// pages/listeningDetail/listeningDetail.js
let util = require("../../utils/util.js");
let WxParse = require('../../wxParse/wxParse.js');
const innerAudioContext = wx.getBackgroundAudioManager();
Page({
    //分享
    onShareAppMessage: function () { },
    /**
     * 页面的初始数据
     */
    data: {
        audioCtx: "",
        progress: 20,//进度条进度
        audioSrc: "",
        curTimeVal: "00:00",
        endTime: "00:00",
        runTime: 0,
        isPlayed: false,
        isFirst: true,//是不是第一次播放,
        bookId: '',
        detail: {},
        audioList: [],
        bookList: [],
        commentList: [],
        pageNumber: 1,
        readMoreFlag: false,
        playindex: 0,
        bookImg: '',
        endTime: 0,
        myPublish: '',
        hiddenDetailFlag: true,//是否收起书籍详情 true-显示  false-收起
        innerAudioContext: "",
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            bookId: options.id
        });
        this.getDetail();
    },
    //获取书籍详情
    getDetail: function () {
        var that = this;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.id;
        var bookId = this.data.bookId;
        util.wxAjax("glBook/detail", "post", {
            id: bookId,
            adminid: userInfo
        }, function (res) {
            var data = res.data;
            if (data.result == 200) {
                wx.setStorageSync("listenBookId", bookId);
                wx.hideNavigationBarLoading();
                wx.stopPullDownRefresh();
                wx.hideLoading();
                WxParse.wxParse('article1', 'html', data.data.glBook.about, that, 0);
                that.setData({
                    detail: data.data,
                    audioSrc: data.data.sections[0].sectionUrl,
                    audioList: data.data.sections,
                    bookList: data.data.glBook,
                    commentList: data.data.commentList,
                    readMoreFlag: data.data.commentList.length > 19 ? true : false
                });
                //判断是否进来同一本书还是另外一本书
                var listenBookUrl = wx.getStorageSync("listenBookUrl");
                var listenBookIndex = wx.getStorageSync("listenBookIndex");
                var audioSrc = data.data.sections[listenBookIndex].sectionUrl;
                if (!!audioSrc && audioSrc != "") {
                    if (audioSrc == listenBookUrl) {
                        that.updateTime(that);
                    }
                }
                wx.setStorageSync("listenBookUrl", audioSrc);
            }
        })
    },
    bookmoreCommon: function () {
        let bookId = this.data.bookId;
        let adminid = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.id;
        let commentList = this.data.commentList;
        let pageNum = this.data.pageNumber;
        var that = this;
        util.wxAjax("glBook/bookmoreCommon", "post", {
            id: bookId,
            adminid: adminid,
            pageNum: pageNum
        }, function (res) {
            var data = res.data;
            if (!!data.data) {
                wx.hideNavigationBarLoading();
                wx.stopPullDownRefresh();
                wx.hideLoading();
                commentList = commentList.concat(data.data);
                that.setData({
                    commentList: commentList
                });
            } else {
                wx.hideNavigationBarLoading();
                wx.stopPullDownRefresh();
                wx.hideLoading();
            }
        });
    },
    //上拉刷新
    onPullDownRefresh: function () {
        // 显示顶部刷新图标  
        wx.showNavigationBarLoading();
        this.setData({
            pageNumber: 1,
            commentList: []
        });
        this.getDetail();
    },
    //下拉加载
    onReachBottom: function () {
        var flag = this.data.readMoreFlag;
        if (flag) {
            var pageNum1 = this.data.pageNumber;
            // 显示加载图标  
            wx.showLoading({
                title: '玩命加载中',
            })
            this.setData({
                pageNumber: ++pageNum1,
            });
            this.bookmoreCommon();
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },
    play: function () {
        wx.showLoading({
            title: '加载中...',
        })
        var that = this;
        var index = this.data.playindex;
        var bookDetail = this.data.audioList[index];
        var bookList = this.data.bookList;
        // innerAudioContext.stop();
        innerAudioContext.title = bookDetail.sectionName;
        innerAudioContext.epname = bookDetail.sectionName;
        innerAudioContext.singer = bookList.anchorName;
        innerAudioContext.coverImgUrl = bookList.img;
        innerAudioContext.src = this.data.audioSrc;
        wx.setStorageSync("listenBookImg", bookList.img);
        wx.setStorageSync("listenBookName", bookDetail.sectionName);
        wx.setStorageSync("listenBookUrl", this.data.audioSrc);
        wx.setStorageSync("listenBookIndex", index);
        // innerAudioContext.play();
        innerAudioContext.onPlay(() => {
            console.log(innerAudioContext);
            var isPlayed = this.data.isPlayed;
            var isFirst = this.data.isFirst;
            that.updateTime(that);
            if (!isPlayed) {
                if (isFirst) {
                    that.setData({
                        isFirst: false
                    });
                }
                that.setData({
                    isPlayed: true,
                });
            }
        });
        setTimeout(function () {
            var oldSrc = wx.getStorageSync("listenBookUrl");
            if (innerAudioContext.src == "" || !innerAudioContext.src) {
                innerAudioContext.src = oldSrc;
            }
            innerAudioContext.play();
            wx.hideLoading();
            if (!!innerAudioContext.duration && innerAudioContext.duration <= 0) {
                innerAudioContext.stop();
                wx.showToast({
                    title: '加载失败，请点击播放重新加载~',
                    icon: "none"
                })
            }
        }, 2000);
    },
    pause: function () {
        var that = this;
        innerAudioContext.pause();
        setTimeout(function () {
            that.setData({
                isPlayed: false
            });
        }, 300)
    },
    updateTime: function (that) {
        wx.hideLoading();
        innerAudioContext.onTimeUpdate((res) => {
            var isPlayed = that.data.isPlayed;
            //更新时把当前的值给slide组件里的value值。slide的滑块就能实现同步更新
            var duration = innerAudioContext.duration.toFixed(2) * 100;
            var runTime = innerAudioContext.currentTime.toFixed(2) * 100;
            if (!!runTime && runTime > 0 && !isPlayed) {
                that.setData({
                    isPlayed: true
                });
            }
            that.setData({
                duration: duration,
                curTimeVal: that.changeTime(innerAudioContext.currentTime.toFixed(2)),
                runTime: runTime,
                endTime: that.changeTime(innerAudioContext.duration.toFixed(2))
            });
            //播放到最后一秒
            if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
                that.setStopState(that, duration, runTime)
            }
            innerAudioContext.onEnded(() => {
                that.setStopState(that, duration, runTime)
            })
        })
    },
    //拖动滑块
    slideBar: function (e) {
        let that = this;
        var curval = e.detail.value; //滑块拖动的当前值
        console.log(curval)
        innerAudioContext.seek(Math.floor(curval / 100)); //让滑块跳转至指定位置
        innerAudioContext.onSeeked((res) => {
            this.updateTime(that) //注意这里要继续出发updataTime事件，
        });
    },
    setStopState: function (that, duration, runTime) {
        that.setData({
            curTimeVal: "00:00",
            isPlayed: false
        })
        if (duration == 0 && runTime == 0) {
            innerAudioContext.stop();
            that.setData({
                runTime: 0,
            });
        } else {
            this.nextAudio();
        }
    },
    //将秒数变成时间
    changeTime: function (time) {
        var minute = Math.floor(time / 60) < 10 ? "0" + Math.floor(time / 60) : Math.floor(time / 60);
        var second = Math.ceil(time % 60) < 10 ? "0" + Math.ceil(time % 60) : Math.ceil(time % 60);
        return minute + ":" + second;
    },
    //点击章节列表开始播放
    start_play: function (e) {
        var oldSrc = wx.getStorageSync("listenBookUrl");
        innerAudioContext.stop();
        var index = e.currentTarget.dataset.index;
        var msg = e.currentTarget.dataset.msg;
        var that = this;
        var endtime = this.changeTime(msg.sectionSec);
        this.setData({
            playindex: index,
            audioSrc: msg.sectionUrl,
            endTime: endtime
        });
        wx.showLoading({
            title: '加载中...',
        })
        that.play();
    },
    //播放上一首
    preAudio: function () {
        var oldSrc = wx.getStorageSync("listenBookUrl");
        if (this.data.playindex > 0) {
            innerAudioContext.stop();
            var that = this;
            var index = --this.data.playindex;
            this.setData({
                playindex: index,
                audioSrc: this.data.audioList[index].sectionUrl
            });
            that.play();
        } else {
            wx.showToast({
                title: '已经是第一章了~',
                icon: "none"
            })
        }
    },
    //播放下一首
    nextAudio: function () {
        var index = this.data.playindex;
        var length = this.data.audioList.length;
        var oldSrc = wx.getStorageSync("listenBookUrl");
        var that = this;
        if (index < --length) {
            index = ++index;
            this.setData({
                playindex: index,
                audioSrc: this.data.audioList[index].sectionUrl
            });
            that.play();
        } else {
            wx.showToast({
                title: '已经是最后一章了~',
                icon: "none"
            })
        }
    },
    //发表评论
    publish: function () {
        if (this.data.myPublish) {
            var userInfo = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.id;
            var that = this;
            var commentList = this.data.commentList;
            util.wxAjax("glBook/updateCommentsAddOne", "post", {
                id: that.data.bookId,
                adminid: userInfo,
                content: that.data.myPublish
            }, function (res) {
                var data = res.data;
                var temp = [];
                if (data.result == 200 || data.result == "200") {
                    that.getDetail();
                    that.setData({
                        myPublish: ""
                    });
                } else {
                    wx.showToast({
                        title: '评论失败！',
                        icon: 'none'
                    })
                }
            })
        } else {
            wx.showToast({
                title: '请输入评论信息！',
                icon: "none"
            });
        }
    },
    //获取留言板的内容
    getTextArea: function (e) {
        var value = e.detail.value;
        this.setData({
            myPublish: value
        })
    },
    //收起书籍详情
    hiddenDetail: function () {
        var hiddenDetailFlag = this.data.hiddenDetailFlag;
        this.setData({
            hiddenDetailFlag: !hiddenDetailFlag
        });
    },
    //书籍点赞
    dianzan: function () {
        var that = this;
        var bookList = this.data.bookList;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        util.wxAjax("glBook/updateBookLaudsAddOne", "post", {
            adminid: userInfo.smAdmin.id,
            id: bookList.id
        }, function (res) {
            var data = res.data;
            if (data.result == 200 || data.reslut == "200") {
                wx.showToast({
                    title: '点赞成功！',
                })
                bookList.lauds = data.data;
                bookList.isLauds = 1;
                that.setData({
                    bookList: bookList
                });
            } else {
                wx.showToast({
                    title: data.msg,
                    icon: "none"
                })
            }
        });
    },
    //评论点赞
    pinglunDianzan: function (options) {
        var that = this;
        var books = this.data.bookList;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        var id = options.currentTarget.dataset.id;
        var index = options.currentTarget.dataset.index;
        var commentList = this.data.commentList;
        util.wxAjax("glBook/updateLaudsAddOne", "post", {
            contentId: books.id,
            adminid: userInfo.smAdmin.id,
            id: id
        }, function (res) {
            var data = res.data;
            if (data.reslut == 200 || data.result == "200") {
                commentList[index].lauds += 1;
                commentList[index].isLauds = 1;
                that.setData({
                    commentList: commentList
                });
            } else {
                wx.showToast({
                    title: data.msg,
                    icon: "none"
                })
            }
        });
    },
    //删除评论
    deleteContent: function (options) {
        var that = this;
        var id = options.currentTarget.dataset.id;
        var index = options.currentTarget.dataset.index;
        var commentList = this.data.commentList;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        wx.showModal({
            title: '确认信息',
            content: '确认要删除当前评论吗？',
            success: function (res) {
                if (res.confirm) {
                    util.wxAjax("glBook/deleteCommon", "post", {
                        id: id,
                        adminid: userInfo.smAdmin.id
                    }, function (res) {
                        var data = res.data;
                        if (data.result == 200 || data.result == "200") {
                            commentList.splice(index, 1);
                            that.setData({
                                commentList: commentList
                            });
                            wx.showToast({
                                title: '删除成功！',
                                icon: "none"
                            })
                        } else {
                            wx.showToast({
                                title: data.msg,
                                icon: "none"
                            })
                        }
                    })
                }
            }
        })
    }
})